﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace Calculator
{
    public partial class AreaConvert : UserControl
    {
        public AreaConvert()
        {
            InitializeComponent();
        }

        private void ConvertButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 获取输入值
                double input = double.Parse(InputTextBox.Text);

                // 获取输入和输出单位
                string inputUnit = ((ComboBoxItem)InputUnitComboBox.SelectedItem).Content.ToString();
                string resultUnit = ((ComboBoxItem)ResultUnitComboBox.SelectedItem).Content.ToString();

                // 计算转换结果
                double result = ConvertArea(input, inputUnit, resultUnit);

                // 显示结果
                ResultTextBox.Text = result.ToString("F2");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"转换失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private double ConvertArea(double value, string fromUnit, string toUnit)
        {
            // 面积单位的换算关系（单位为平方米）
            var unitFactors = new Dictionary<string, double>
            {
                {"平方米", 1},
                {"平方千米", 1_000_000},
                {"平方分米", 0.01},
                {"平方厘米", 0.0001},
                {"平方毫米", 0.000001},
                {"平方微米", 0.000000000001},
                {"平方公里", 1_000_000},
                {"公顷", 10_000},
                {"公亩", 100},
                {"亩", 666.6667},
                {"平方尺", 0.092903},
                {"平方寸", 0.00064516},
                {"平方英里", 2_589_988.11},
                {"英亩", 4_046.85642},
                {"平方竿", 25.29285264},
                {"平方码", 0.836127},
                {"平方英尺", 0.092903},
                {"平方英寸", 0.00064516}
            };

            // 转换为平方米
            if (!unitFactors.ContainsKey(fromUnit) || !unitFactors.ContainsKey(toUnit))
                throw new InvalidOperationException("无效的单位");

            double valueInSquareMeters = value * unitFactors[fromUnit];

            // 从平方米转换为目标单位
            return valueInSquareMeters / unitFactors[toUnit];
        }
    }
}
